package com.yumeng.common.data.validator;

import com.yumeng.common.data.validator.annotation.DateFormat;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * @author wxd
 * @date 2022/10/25 16:32
 */
public class DateValidator implements ConstraintValidator<DateFormat, String> {

    private DateFormat constraintAnnotation;

    @Override
    public void initialize(DateFormat constraintAnnotation) {
        this.constraintAnnotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 如果 value 为空则不进行格式验证，为空验证可以使用 @NotBlank @NotNull @NotEmpty 等注解来进行控制，职责分离
        if (StringUtils.isBlank(value)) {
            return true;
        }
        String format = this.constraintAnnotation.format();
        if (value.length() != format.length()) {
            return false;
        }
        try {
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern(format);
            LocalDate.parse(value, fmt);
        } catch (DateTimeParseException | IllegalArgumentException e){
            return false;
        }
        return true;
    }
}
